﻿using System;
using System.Collections.Generic;
using System.Text;
using Cashier_DAO.db;
using Cashier_Model;
using Cashier_DAO;
using System.Data;
using Cashier_Utils;
using System.Data.Common;

namespace Cashier_Service
{
    public class MemberService
    {
        /// <summary>
        /// 查询Member
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Member GetMember(long id, String memberno)
        {
            Member member = null;
            try
            {
                using (DbConnection conn = ConnectionFactory.GetDbConnection())
                {
                    conn.Open();
                    member = new Member();
                    member.Id = id;
                    member.Memberno = memberno;
                    member = new MemberDAO().GetMember(conn, member);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return member;
        }

        /// <summary>
        /// 通过手机号查找会员
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public Member GetMemberByMobile(String mobile)
        {
            Member member = null;
            try
            {
                using (DbConnection conn = ConnectionFactory.GetDbConnection())
                {
                    conn.Open();
                    member = new Member();
                    member.Mobile = mobile;
                    member = new MemberDAO().GetMember(conn, member);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return member;
        }

        /// <summary>
        /// 查询Member列表
        /// </summary>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <param name="enterpriseNo"></param>
        /// <param name="memberno"></param>
        /// <param name="name"></param>
        /// <param name="mobile"></param>
        /// <param name="adminUsername"></param>
        /// <param name="ascfield"></param>
        /// <param name="descfield"></param>
        /// <returns></returns>
        public DataTable GetMemberTable(int pageindex, int pagesize, String enterpriseNo, String memberno, String name, String mobile, 
            String adminUsername, String ascfield, String descfield)
        {
            DataTable dt = null;
            try
            {
                using (DbConnection conn = ConnectionFactory.GetDbConnection())
                {
                    conn.Open();
                    Member member = new Member();
                    member.Pageindex = pageindex;
                    member.Pagesize = pagesize;
                    member.EnterpriseNo = enterpriseNo;
                    member.Memberno = memberno;
                    member.Name = name;
                    member.Mobile = mobile;
                    member.AdminUsername = adminUsername;
                    member.Ascfield = ascfield;
                    member.Descfield = descfield;
                    dt = new MemberDAO().GetMemberTable(conn, member);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return dt;
        }

        /// <summary>
        /// 查询会员记录数
        /// </summary>
        /// <param name="enterpriseNo"></param>
        /// <param name="memberno"></param>
        /// <param name="name"></param>
        /// <param name="mobile"></param>
        /// <param name="adminUsername"></param>
        /// <returns></returns>
        public long GetMemberRecord(String enterpriseNo, String memberno, String name, String mobile, String adminUsername)
        {
            long record = 0;
            try
            {
                using (DbConnection conn = ConnectionFactory.GetDbConnection())
                {
                    conn.Open();
                    Member member = new Member();
                    member.EnterpriseNo = enterpriseNo;
                    member.Memberno = memberno;
                    member.Name = name;
                    member.Mobile = mobile;
                    member.AdminUsername = adminUsername;
                    record = new MemberDAO().GetMemberRecord(conn, member);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return record;
        }

        /// <summary>
        /// 插入Member
        /// </summary>
        /// <param name="member"></param>
        /// <returns></returns>
        public long InsertMember(Member member)
        {
            long id = 0;
            DbTransaction trans = null;
            using (DbConnection conn = ConnectionFactory.GetDbConnection())
            {
                try
                {
                    conn.Open();
                    trans = conn.BeginTransaction();
                    id = new MemberDAO().InsertMember(conn, member);
                    if (id > 0 && member.Balance != null && member.Balance > 0)
                    {
                        //保存充值记录
                        MemberRecharge memberRecharge = new MemberRecharge();
                        memberRecharge.EnterpriseNo = member.EnterpriseNo;
                        memberRecharge.StoreNo = member.StoreNo;
                        memberRecharge.TransNo = GuidUtil.GetGuidToLong().ToString();
                        memberRecharge.MemberNo = member.Memberno;
                        memberRecharge.Money = member.Balance;
                        memberRecharge.RechargeTime = DateTime.Now;
                        memberRecharge.Note = "创建会员并首次充值";
                        memberRecharge.AdminUsername = member.AdminUsername;
                        memberRecharge.AdminName = member.AdminName;
                        memberRecharge.CreateTime = DateTime.Now;
                        new MemberRechargeService().InsertMemberRecharge(conn, memberRecharge);
                    }
                    trans.Commit();
                }
                catch (Exception ex)
                {
                    if (trans != null)
                        trans.Rollback();
                    throw ex;
                }
                finally
                {
                    if (trans != null)
                        trans = null;
                }
            }           
            return id;
        }

        /// <summary>
        /// 更新Member信息
        /// </summary>
        /// <param name="member"></param>
        /// <returns></returns>
        public int UpdateMember(Member member)
        {
            int flag = 0;
            try
            {
                using (DbConnection conn = ConnectionFactory.GetDbConnection())
                {
                    conn.Open();
                    flag = new MemberDAO().UpdateMemeber(conn, member);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return flag;
        }

        /// <summary>
        /// 删除Member
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public int DeleteMember(String ids)
        {
            int count = 0;
            try
            {
                if (!String.IsNullOrEmpty(ids))
                {
                    using (DbConnection conn = ConnectionFactory.GetDbConnection())
                    {
                        conn.Open();
                        MemberDAO memberDAO = new MemberDAO();
                        Member member = new Member();
                        String[] idArr = ids.Split(new Char[] { ',' });
                        foreach (String lopid in idArr)
                        {
                            member.Id = Int64.Parse(lopid);
                            count += memberDAO.DeleteMember(conn, member);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return count;
        }

        /// <summary>
        /// 更新用户积分
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="memberno">用户编号</param>
        /// <param name="historyInteger">历史积分</param>
        /// <param name="integral">当前增长/消费积分</param>
        /// <param name="integralEnum">积分类型</param>
        /// <returns></returns>
        public int UpdateMemberIntegral(DbConnection conn, String memberno, int historyInteger, int integral, IntegralEnum integralEnum)
        {
            int flag = 0;
            try
            {
                Member member = this.GetMember(0, memberno);
                if (member != null)
                {
                    if (historyInteger > 0)
                    {
                        member.HistoryIntegral += historyInteger;
                    }
                    if (integralEnum == IntegralEnum.IN)
                    {
                        member.CurrentIntegral += integral; 
                    }
                    else if (integralEnum == IntegralEnum.OUT)
                    {
                        if (member.CurrentIntegral >= integral)
                        {
                            member.CurrentIntegral -= integral;
                        }
                        else
                        {
                            member.CurrentIntegral = 0;
                        }
                    }
                    flag = new MemberDAO().UpdateMemberIntegral(conn, member);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return flag;
        }

        /// <summary>
        /// 更新会员卡内余额
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="memberno"></param>
        /// <param name="balance"></param>
        /// <param name="balanceEnum"></param>
        /// <returns></returns>
        public int UpdateMemberBalance(DbConnection conn, String memberno, Decimal balance, BalanceEnum balanceEnum)
        {
            int flag = 0;
            try
            {
                Member member = this.GetMember(0, memberno);
                if (member != null)
                {
                    if (balanceEnum == BalanceEnum.IN)
                        member.Balance += balance;
                    else if (balanceEnum == BalanceEnum.OUT)
                    {
                        if (member.Balance >= balance)
                            member.Balance -= balance;
                        else
                            member.Balance = 0;
                    }
                    flag = new MemberDAO().UpdateMemberBalance(conn, member);
                }
                else
                    throw new Exception("Member is not exist!");
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return flag;
        }

        /// <summary>
        /// 清空会员积分
        /// </summary>
        /// <param name="memberno"></param>
        /// <param name="memberIntegral"></param>
        /// <returns></returns>
        public int ClearMemberIntegral(String memberno, MemberIntegral memberIntegral)
        {
            int flag = 0;
            Member member = this.GetMember(0, memberno);
            if (member != null)
            {
                using (DbConnection conn = ConnectionFactory.GetDbConnection())
                {
                    DbTransaction trans = null;
                    try
                    {
                        conn.Open();
                        trans = conn.BeginTransaction();
                        int temp_integral = member.CurrentIntegral;
                        member.CurrentIntegral = 0;
                        flag = new MemberDAO().UpdateMemberIntegral(conn, member);

                        memberIntegral.MemberNo = memberno;
                        memberIntegral.Type = (Int32)IntegralEnum.OUT;
                        memberIntegral.IsSuccess = flag > 0 ? true : false;
                        memberIntegral.CreateTime = DateTime.Now;
                        new MemberIntegralService().InsertMemberIntegral(conn, memberIntegral);
                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        if (trans != null)
                            trans.Rollback();
                        throw ex;
                    }
                    finally
                    {
                        if (trans != null)
                            trans = null;
                    }
                }
            }
            else
                throw new Exception("Member is not exist!");
            return flag;
        }
    }
}
